"use strict";

angular.module('app.yksensor').controller('SensorProtocolConCtrl', function ($scope,$element,$stateParams,sensorHttpS) {

    // HTTPDataService.getSystemConfig().then(function (response) {

    //     $scope.systemDate = response;
    // });
  //配置分页基本参数
   // $scope.paginationConf = {
   //     currentPage: 1,
   //     itemsPerPage: 10,
   //     pagesLength: 5,
   //     totalItems: 20,
   //     perPageOptions: [10, 20, 30, 40, 50],
   //     onChange: function () {
   //     }
   // };
  var tableName = 'protocol' + $stateParams.protocolid;
  console.log(tableName);
  $scope.finally_name = '';
  //显示数据库的数据
  var GetData = function () {
      sensorHttpS.get(tableName).then(function (response) { 
           console.log(response);
           for (var i = 0; i < response.length; i++) {
             var ss = response[i].Type.match(/(\S*)\(/)[1];
             response[i].type1 = ss;
           }
           $scope.sensorProtocolInfo = response;
           $scope.finally_name = response[response.length-1].Field;
           // $scope.paginationConf.totalItems = response['sum'];
      });

  }
   GetData();
    // str="2,2,3,5,6,6"; //这是一字符串 
    // var strs= new Array(); //定义一数组 
    // strs=str.split(","); //字符分割 
    // for (i=0;i<strs.length ;i++ ) 
    // { 
    // document.write(strs[i]+"<br/>"); //分割后的字符输出 
    // } 
// $scope.$watch('paginationConf.currentPage + paginationConf.itemsPerPage', GetData);
//编辑数据
var flag = false;
var arr = [];
var rowOld;
$scope.edit_obj = {};
$scope.editSensorProtocol = function(row){
 $("#label"+row).removeAttr("readonly");
 $("#label"+row).removeClass("inputEdit");
 $(".length"+row).removeAttr("readonly");
 $(".length"+row).removeClass("inputEdit");
 $("#type"+row).removeClass("ng-hide");
 $(".type"+row).addClass("ng-hide"); 
 rowOld = row;
}
//保存数据
$scope.saveSensorProtocol = function(row){
  console.log(row);
  var label = $("#label"+row).val();
  var type = $("#type"+row).val();
  var length1 = $(".length"+row).val();
  var length2 = $(".xiao"+row).val();
  var comment = $(".comment"+row).val();
  var n1 = Number(length1);
  var n2 = Number(length2); 
  var checkname = checkUser(label);
  if(checkname == false){
    alert("名字由字母数字下划线组成，字母开头");
    return;
  }else if(isNaN(n1) && isNaN(n2)){
    alert("长度和小数位数都是数字！！");
    return;
  }else if(n1 < n2){
    alert("小数点不能比长度大！");
    return;
  }
   $("#label"+row).attr("readonly",true);
   $("#label"+row).addClass("inputEdit");
   $(".length"+row).attr("readonly",true);
   $(".length"+row).addClass("inputEdit");
   $(".type"+row).removeClass("ng-hide");
   $("#type"+row).addClass("ng-hide");
 if(length.length == 0){
     //设置默认的length 
    if(type == "int"){
       length = "11";
    }else if(type == "double"){
       length = "16,2";
    }else if(type == "float"){
       length = "50,4";
    }else if(type == "varchar"){
       length = "50";
    }
 }
    if(type == "int"){
       length = length1;
    }else if(type == "double"){
       length = length1+","+length2;
    }else if(type == "float"){
       length = length1+","+length2;
    }else if(type == "varchar"){
       length = length1;
    }   
  //保存修改的数据
    var old_name = rowOld;
    var new_name = $("#label"+row).val(); 
    var save_data = {};
    save_data.old_name = old_name;
    save_data.new_name = new_name;
    save_data.type = type;
    save_data.max_length = length;
    save_data.comment = comment;
    $scope.edit_obj.oper = "edit";
    $scope.edit_obj.table_name = tableName;
    $scope.edit_obj.data = save_data;
    console.log($scope.edit_obj);
    sensorHttpS.postAll('editProtocolCon',$scope.edit_obj).then(function (response) {
    console.log(response);
    if (response > 0) {
        GetData();
        $scope.edit_obj = {};
        $.smallBox({
            title: "编辑协议成功",
            content: "<i class='fa fa-clock-o'></i> <i>编辑协议成功</i>",
            color: "#659265",
            iconSmall: "fa fa-check fa-2x fadeInRight animated",
            timeout: 4000
        });
    }
    else {

    }

    })

}
//增加一行数据,添加到表格的最后
$scope.add_obj = {};
var addData = {};
$scope.addRowData = function(){ 
	  var new_row = add_dom();
    $("tbody").prepend(new_row);   
    addData.position = "after";
    addData.position_con = $scope.finally_name;
    $("#delRow").click(function(){
       $(".remove_row").remove();
    });
    add_click();
}

// 插入数据
$scope.insertRowData = function(){
    var new_row = add_dom();
    var current_checked = [];
    $("input[type='checkbox']").each(function(obj){
           if($(this).is(":checked")){
              // console.log($(this).parent().parent().parent());
              current_checked.push($(this).parent().parent().parent());
           }
    });
    $(".remove_row").remove();
    console.log(current_checked[0]);
    if(current_checked[0]){
      addData.position = "after";
      addData.position_con = current_checked[0].attr("addname");
      current_checked[0].after(new_row);   
    }else{
      alert("请选择至少一条数据再操作");
      return;
    }
    
    $("#delRow").click(function(){
       $(".remove_row").remove();
    });
    add_click();
}
var add_dom = function(){
  var new_row = $('<tr class="remove_row">'+
                    '<td>'+
                    '</td>'+
                    '<td>'+                        
                       ' <button class="btn btn-xs btn-default" id="addData" uib-tooltip="保存" tooltip-append-to-body="true" ><i class="fa fa-save"></i></button>&nbsp;'+
                       '<button class="btn btn-xs btn-default"  id="delRow" uib-tooltip="删除" tooltip-append-to-body="true" ><i class="fa fa-times"></i></button>'+
                   ' </td>'+
                    '<td>'+
                    '<input type="text" class="labels" />'+                                               
                    '</td>'+
                    '<td>'+
                   ' <select class="types"> ' +
                                       '   <option value="int">int</option> ' +
                                        '  <option value="double">double</option> '+ 
                                        '  <option value="float">float</option> ' +
                                         ' <option value="varchar">varchar</option> '+ 
                                    '  </select>' +
                    '</td>'+
                   ' <td>'+
                   ' <input type="text" class="lengths" />'+
                    '</td>'+
                    ' <td>'+
                   ' <input type="text" class="decimal" />'+
                    '</td>'+
                    ' <td>'+
                   ' <input type="text" class="comment" />'+
                    '</td>'+
                '</tr>');
  return new_row;
}
var add_click = function(){
   $("#addData").click(function(){
      var label = $(".labels").val();
      var length1 = $(".lengths").val();
      var length2 = $(".decimal").val();
      var comment = $(".comment").val();
      var n1 = Number(length1);
      var n2 = Number(length2);
      var type = $(".types option:checked").val();   
      var checkname = checkUser(label);
      if(checkname == false){
        alert("名字由字母数字下划线组成，字母开头");
        return;
      }else if(isNaN(n1) && isNaN(n2)){
        alert("长度和小数位数都是数字！！");
        return;
      }else if(n1 < n2){
        alert("小数点不能比长度大！");
        return;
      }
      // 设置默认
      if(length.length == 0){
        //设置默认的length 
        if(type == "int"){
           length = "11";
        }else if(type == "double"){
           length = "16,2";
        }else if(type == "float"){
           length = "50,4";
        }else if(type == "varchar"){
           length = "50";
        }
      }
        if(type == "int"){
           length = length1;
        }else if(type == "double"){
           length = length1+","+length2;
        }else if(type == "float"){
           length = length1+","+length2;
        }else if(type == "varchar"){
           length = length1;
        }   
        addData.name = label;
        addData.type = type;
        addData.max_length = length;
        addData.comment = comment;
        $scope.add_obj.oper = "add";
        $scope.add_obj.table_name = tableName;
        $scope.add_obj.data = addData;
        console.log($scope.add_obj);
        sensorHttpS.postAll('editProtocolCon',$scope.add_obj).then(function (response) {
            if (response > 0) { 
                $(".remove_row").remove();
                //添加成功后重新访问数据库 
                $scope.add_obj = {};   
                addData = {};       
                GetData();             
                $.smallBox({
                    title: "添加协议成功",
                    content: "<i class='fa fa-clock-o'></i> <i>添加协议成功</i>",
                    color: "#659265",
                    iconSmall: "fa fa-check fa-2x fadeInRight animated",
                    timeout: 4000
                });
            }
            else {

            }

        })
    })
}
//删除数据
$scope.del_obj = {};
$scope.showDelDialog = function (name) {
       $scope.del_obj.oper = "del";
       $scope.del_obj.table_name = tableName;
       var data_obj = {};
       data_obj.name = name;
       $scope.del_obj.data = data_obj;
        $('#showDelDialog').modal('show');

 }
$scope.delSensorProtocol = function(){
  $('#showDelDialog').modal('hide');
  console.log($scope.del_obj);
  sensorHttpS.postAll('editProtocolCon',$scope.del_obj).then(function (response) {
	    if (response > 0) {
	        GetData();	
          $scope.del_obj = {};       
	        $.smallBox({
	            title: "删除协议成功",
	            content: "<i class='fa fa-clock-o'></i> <i>删除协议成功</i>",
	            color: "#659265",
	            iconSmall: "fa fa-check fa-2x fadeInRight animated",
	            timeout: 4000
	        });

	    }
	    else {

	    }

	})
}
// 单选改变样式
  var choseArr = [];
  // 全选 
  $scope.all= function (m,item) {   
       if (m === false) {
          $scope.selectAll=false; 
          choseArr = [];         
       }else{
          $scope.selectAll=true;
          choseArr = [];
          for(var i = 0; i < item.length; i++){
              var obj = {};
              obj.name = item[i].name;
              choseArr.push(obj);
          }
          console.log(choseArr);
       }

  };  
  $scope.x=false;//默认未选中
  $scope.checked = function(item,x){
      // item为数据，x为是否选中true，false
      var object = {"name":item.name};
      if (x == true) {//选中
         choseArr.push(object);
      }else{//取消选中
         console.log(x);
         delete_arr(item);
      }
      console.log(choseArr);
  }
    // 删除数组中指定的对象
    var delete_arr = function(item){
      console.log(item.name);
         for(var i = 0; i < choseArr.length; i++){
            var obj = choseArr[i];
            if(item.name == obj.name){
                choseArr.splice(i, 1);
                break;
            }
        }
    }
    //显示删除对话框
    $scope.delectCheckShow = function(){
        if(choseArr.length > 0){
            $('#showDelDialog2').modal('show');
        }else{
            alert("请选择至少一条数据再操作");
        }
        
    }
   // 多选删除
     $scope.delectCheck = function(){
        $('#showDelDialog2').modal('hide');
        var data = {"choseArr":choseArr};
        console.log(data);
        sensorHttpS.postAll('delProtocolConMore',tableName, data).then(function (response) {
            console.log(response);
            if (response > 0) {
            	
                GetData();
                choseArr = [];
                $.smallBox({
                    title: "删除传感器成功",
                    content: "<i class='fa fa-clock-o'></i> <i>删除传感器成功</i>",
                    color: "#659265",
                    iconSmall: "fa fa-check fa-2x fadeInRight animated",
                    timeout: 4000
                });

            }
            else {
            	console.log(response);
            }

        })
        
     }


});
// 字母、数字、下划线组成，字母开头，1-16位。
var  checkUser = function(str){
    var re = /^[a-zA-z]\w{0,15}$/;
    if(re.test(str)){
        return true;
    }else{
        return false;
    }
}          